<template>
	<view class="history-container">
		<!-- 历史记录列表 -->
		<view class="history-list" v-if="historyList.length > 0">
			<view class="history-item" v-for="item in historyList" :key="item.id" @tap="goToDetail(item.goods_id)">
				<image :src="item.img_url" mode="aspectFill" class="goods-image"></image>
				<view class="goods-info">
					<view class="goods-name">{{ item.title }}</view>
					<view class="goods-price">¥{{ item.sell_price }}</view>
					<view class="goods-buy">已售 {{ item.buy }}</view>
				</view>
			</view>
		</view>

		<!-- 空状态 -->
		<view class="empty-state" v-else>
			<image src="/static/images/empty-image-error.png" mode="aspectFit" class="empty-image"></image>
			<text class="empty-text">暂无浏览记录</text>
		</view>
	</view>
</template>

<script setup>
import { ref } from 'vue';
import { reqHistory } from '@/api/user';
import { useUserStore } from '@/store/index';
import { onLoad } from '@dcloudio/uni-app';

const userStore = useUserStore();
const historyList = ref([]);
const page = ref(1);
const pagesize = ref(10);

// 获取历史记录
const getHistoryList = async () => {
	try {
		const res = await reqHistory({
			page: page.value,
			pagesize: pagesize.value
		});
		historyList.value = res
	} catch (error) {
		console.error('获取历史记录失败:', error);
		uni.showToast({
			title: '获取历史记录失败',
			icon: 'none'
		});
	}
};

// 跳转到商品详情
const goToDetail = (goodsId) => {
	uni.navigateTo({
		url: `/pages/goods_package/goodsdetail/goodsdetail?id=${goodsId}`
	});
};

// 页面加载时获取历史记录
onLoad(() => {
	if (userStore.token) {
		getHistoryList();
	} else {
		uni.showToast({
			title: '请先登录',
			icon: 'none'
		});
		setTimeout(() => {
			uni.navigateTo({
				url: '/pages/user_package/login/login'
			});
		}, 500);
	}
});
</script>

<style lang="scss" scoped>
.history-container {
	min-height: 100vh;
	background-color: #f8f8f8;
	padding: 20rpx;

	.history-list {
		.history-item {
			display: flex;
			padding: 20rpx;
			background: #fff;
			border-radius: 12rpx;
			margin-bottom: 20rpx;

			.goods-image {
				width: 160rpx;
				height: 160rpx;
				border-radius: 8rpx;
				margin-right: 20rpx;
			}

			.goods-info {
				flex: 1;
				display: flex;
				flex-direction: column;
				justify-content: space-between;

				.goods-name {
					font-size: 28rpx;
					color: #333;
					line-height: 1.4;
					margin-bottom: 10rpx;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 2;
					overflow: hidden;
				}

				.goods-price {
					font-size: 32rpx;
					color: #ff4444;
					font-weight: bold;
				}

				.goods-buy {
					font-size: 24rpx;
					color: #999;
					margin-top: 10rpx;
				}
			}
		}
	}

	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding-top: 200rpx;

		.empty-image {
			width: 200rpx;
			height: 200rpx;
			margin-bottom: 20rpx;
		}

		.empty-text {
			font-size: 28rpx;
			color: #999;
		}
	}
}
</style>
